﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xc.DataAccess.Core;
using Xc.DataAccess.Core.Services;

namespace Xc.Logics.AepCoap.Services
{
    /// <summary>
    /// CSV文件服务
    /// </summary>
    internal class CsvService : ICsvService
    {
        private readonly IEncodingService _encodingService;

        public CsvService(IEncodingService encodingService)
        {
            _encodingService = encodingService;
        }

        /// <summary>
        /// 写入到文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="value"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public Result WriteToFile(string fileName, List<string[]> value, string[] headers=null)
        {
            try
            {
                List<string> vs = new List<string>();
                if (!File.Exists(fileName))
                {
                    var result = string.Join(",", headers.Select(p=>$"'{p}'"));
                    vs.Add(result);

                }
                foreach (var item in value)
                {
                    var template = string.Join(",", item.Select(p => $"'{p}'"));
                    vs.Add(template);
                }
                File.AppendAllLines(fileName, vs.ToArray(), _encodingService.GetGB2312());
                return Result.Accept("写入成功");
            }
            catch (Exception err)
            {
                return Result.Reject(err.Message);
            }

        }
    }
}
